package utils;

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.net.URL;
import java.util.Properties;

public class PropertyUtil implements Serializable {
	
	private static final long serialVersionUID = 1L;
	
	public static Properties getProperties(String fileName) {
		try {
			URL url = getPropertiesURL(fileName);
			return getProperties(url);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static void setProperties(String propertyFile, String[] parameterName, String[] parameterValue) {
		try {
			URL url = getPropertiesURL(propertyFile);
			setProperties(url, parameterName, parameterValue);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static URL getPropertiesURL(String fileName) {
		try {
			URL url = null;
			url = PropertyUtil.class.getResource("/" + fileName);
			String s = url.toString();
			if (s.indexOf("file://") != -1) {
				int indexOf = s.indexOf("file://") + 6;
				String temp = s.substring(0, indexOf);
				url = new URL(temp + "//" + s.substring(indexOf));
			}
			return url;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static Properties getProperties(URL url) {
		try {
			Properties props = new Properties();
			props.load(url.openStream());
			return props;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static void setProperties(URL url, String[] parameterName, String[] parameterValue) {
		try {
			Properties props = new Properties();
			OutputStream os = new FileOutputStream(url.getFile());
			props.load(url.openStream());
			for (int i = 0; i < parameterName.length; i++)
				props.setProperty(parameterName[i], parameterValue[i]);
			props.store(os, "");
			os.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/*
	 * public static void main(String[] args) throws Exception { URL url = null;
	 * url = PropertyUtil.class.getResource("/" + "website.properties");
	 * Printer.println("此时的url是："+url); String s = url.toString();
	 * Printer.println("此时的s是："+s); if (s.indexOf("file://") != -1) { int
	 * indexOf = s.indexOf("file://") + 6; String temp = s.substring(0,
	 * indexOf); url = new URL(temp + "//" + s.substring(indexOf));
	 * Printer.println("得到的最后url1:"+url); } Printer.println("得到的最后url2:"+url);
	 * Properties props = new Properties(); props.load(url.openStream());
	 * Printer.println("得到的最后props:"+props); }
	 */
}
